package com.homework.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.homework.dto.Result;
import com.homework.entity.Student;
import com.homework.mapper.StudentMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class StudentService {

    private final StudentMapper studentMapper;

    /**
     * 获取所有学生信息
     */
    public Result<List<Student>> getAllStudents() {
        List<Student> students = studentMapper.selectList(null);
        return Result.success(students);
    }

    /**
     * 根据ID获取学生信息
     */
    public Result<Student> getStudentById(Long id) {
        Student student = studentMapper.selectById(id);
        if (student == null) {
            return Result.error("学生不存在");
        }
        return Result.success(student);
    }

    /**
     * 更新学生信息
     */
    public Result<String> updateStudent(Student student) {
        int result = studentMapper.updateById(student);
        if (result > 0) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 获取第一个学生（用于单学生系统）
     */
    public Result<Student> getFirstStudent() {
        Student student = studentMapper.selectOne(
            new LambdaQueryWrapper<Student>().last("LIMIT 1")
        );
        if (student == null) {
            return Result.success("暂无学生信息", null);
        }
        return Result.success(student);
    }

    /**
     * 创建学生
     */
    public Result<String> createStudent(Student student) {
        // 设置创建时间
        if (student.getCreatedAt() == null) {
            student.setCreatedAt(LocalDateTime.now());
        }
        student.setUpdatedAt(LocalDateTime.now());

        int result = studentMapper.insert(student);
        if (result > 0) {
            return Result.success("学生创建成功");
        }
        return Result.error("学生创建失败");
    }
}